package com.lzm.listendemo;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.core.view.ViewCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.app.ActivityOptions;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.hardware.biometrics.BiometricPrompt;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.transition.Slide;
import android.util.Log;
import android.util.Pair;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.transition.platform.MaterialContainerTransformSharedElementCallback;
import com.lzm.base.BaseActivity;
import com.lzm.listendemo.adapter.ArticleAdapter;
import com.lzm.listendemo.adapter.HotKeyAdapter;
import com.lzm.listendemo.bean.Article;
import com.lzm.listendemo.bean.HotKey;
import com.lzm.listendemo.databinding.ActivityMainBinding;
import com.lzm.listendemo.util.HttpUtil;
import com.lzm.listendemo.util.ScreenShotListener;
import com.lzm.listendemo.util.SpUtil;
import com.lzm.listendemo.view.dialog.NotifyDialog;
import com.lzm.listendemo.view.ripple.MyAnimatorThemeView;
import com.lzm.listendemo.view.tick.TickAnimatorListener;
import com.lzm.listendemo.view.tick.TickView;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executor;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends BaseActivity<ActivityMainBinding> {

    private static final String TAG = " MainActivity";

    private ScreenShotListener screenShotListener;

    private boolean isScreenShotListen;



    private ArticleAdapter adapter;

    private int x;
    private int y;
    private long lastDownTime;
    final Handler handler = new Handler();
    final Runnable mLongPressed = new Runnable() {
        @Override
        public void run() {
//            Vibrator vibrator = (Vibrator) MainActivity.this.getSystemService(MainActivity.VIBRATOR_SERVICE);
//            vibrator.vibrate(10);
            mBind.article.setVisibility(View.VISIBLE);
            mBind.article.setThumb(x, y, mBind.article);
            handler.postDelayed(mLongPressed, 100);
        }
    };
    private boolean lightTheme = true;
    boolean isRed = false;

    private MyAnimatorThemeView animatorThemeView;

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 注销广播
        unregisterReceiver(mInstallAppBroadcastReceiver);
    }

    @Override
    protected void onStop() {
        super.onStop();
        isScreenShotListen = false;
    }

    @Override
    public void onResume() {
        super.onResume();
        isScreenShotListen = true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        requestWindowFeature(Window.FEATURE_ACTIVITY_TRANSITIONS);
        getWindow().setExitTransition(new Slide());
        getWindow().requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS);
        setExitSharedElementCallback(new MaterialContainerTransformSharedElementCallback());
        getWindow().setSharedElementsUseOverlay(false);

        super.onCreate(savedInstanceState);

        registerInstallAppBroadcastReceiver();

        new AlertDialog.Builder(this)
                .setTitle("该更新了")
                .setPositiveButton("去更新",(dialog,which)->{
                    SpUtil.getInstance(this).test();
                } )
                .setNegativeButton("取消", (dialog, which) -> Process.killProcess(Process.myPid()))
                .show();


        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mBind.recycler.setLayoutManager(layoutManager);
        mBind.recycler.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));

        /*TextView tv = view.findViewById(ResourceUtils.getIdentifier(this.getContext(), AppConstant.iddd));
        tv.setForceDarkAllowed(false);
        int textcolor = tv.getCurrentTextColor();
        int setColor = Color.parseColor("#B2000000");
        String color = String.format("#%06X", 0xFFFFFF,textcolor);
        Log.e(TAG, "loadedView: getDefaultColor" + tv.getTextColors().getDefaultColor());
        Log.e(TAG, "loadedView: getCurrentTextColor" + tv.getCurrentTextColor());
        Log.e(TAG, "loadedView: setColor" + setColor);
        Log.e(TAG, "loadedView: parse" + getHexString(textcolor));
        Log.e(TAG, "loadedView: " + (setColor == textcolor));*/
        screenShotListener = ScreenShotListener.newInstance(this);
        screenShotListener.startListen((picData, dateTaken) -> {
            if (isScreenShotListen) {
                NotifyDialog notifyDialog = new NotifyDialog(MainActivity.this, R.layout.layout_payment_notify, Gravity.TOP);
                notifyDialog.show();
            }
        });

        mBind.btnNotify.setOnClickListener(v -> {
            NotifyDialog notifyDialog = new NotifyDialog(MainActivity.this, R.layout.layout_payment_notify, Gravity.TOP);
            notifyDialog.findById(R.id.tv_feedback).setOnClickListener(view -> {
                mBind.btnSnackBar.performClick();
            });
            notifyDialog.show();
        });

        mBind.btnSnackBar.setOnClickListener(v -> {
            Snackbar.make(getWindow().getDecorView(), "删除一封邮件", Snackbar.LENGTH_SHORT).setAction("撤销", view -> {
                Toast.makeText(this, "撤回失败", Toast.LENGTH_SHORT).show();
            }).show();
        });

        mBind.btnSwitch.setOnClickListener(v -> {
            NotifyDialog notifyDialog = new NotifyDialog(MainActivity.this, R.layout.layout_loaded, Gravity.CENTER);
            notifyDialog.setOnShowListener(dialog -> ((TickView) notifyDialog.findById(R.id.tick)).toggle());
            ((TickView) notifyDialog.findById(R.id.tick)).getConfig().setTickAnimatorListener(new TickAnimatorListener() {
                @Override
                public void onAnimationStart(TickView tickView) {
                }

                @Override
                public void onAnimationEnd(TickView tickView) {
                    //Looper.getMainLooper()
                    new Handler(Looper.getMainLooper()).postDelayed(notifyDialog::dismiss, 500);

                }
            });
            notifyDialog.show();

            /*animatorThemeView = new MyAnimatorThemeView(this);
            animatorThemeView.setCenterXY(v.getLeft(),v.getTop());
            if(!animatorThemeView.hasStart()){
                animatorThemeView.start();
                lightTheme = !lightTheme;
                updateColor();
            }*/
        });

        mBind.ivLike.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                lastDownTime = System.currentTimeMillis();
                x = (int) event.getRawX();
                y = (int) event.getRawY();
                handler.postDelayed(mLongPressed, 100);
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                mBind.ivLike.setImageResource(isRed ? R.mipmap.like_red : R.mipmap.like_white);
                isRed = !isRed;
                if (System.currentTimeMillis() - lastDownTime < 100) {//判断为单击事件
                    mBind.article.setVisibility(View.VISIBLE);
                    mBind.article.setThumb(x, y, mBind.article);
                }
                handler.removeCallbacks(mLongPressed);
            }
            return true;
        });

        mBind.btnFinger.setOnClickListener(v -> {
            showBiometricPromptDialog(getApplicationContext());
        });

        mBind.btnArticle.setOnClickListener(v->{
            String url = "https://www.wanandroid.com/article/list/0/json";
            HttpUtil.sendRequest(url, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    JSONObject jsonObject = JSON.parseObject(response.body().string());
                    JSONArray array = jsonObject.getJSONObject("data").getJSONArray("datas");
                    List<Article> articles = JSONObject.parseArray(array.toJSONString(), Article.class);
                    Log.e("TAG","" + articles.size());
                    runOnUiThread(()->{
                        adapter = new ArticleAdapter(articles);
                        mBind.recycler.setAdapter(adapter);
                        adapter.setItemOnClick((view, article) -> {
                            view.setTransitionName(article.getLink());
//                            val intent = Intent(context, DetailActivity::class.java)
//                            intent.putExtra(BaseConstant.DETAIL_SHOE_ID, id)
//                            intent.putExtra(CUS_TRANSITION_NAME, transitionName)
//                            if(context is Activity){
//                                context.startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(context, imageView, transitionName).toBundle())
//                            }else {
//                                context.startActivity(intent)
//                            }
                            TextView title = view.findViewById(R.id.text);
                            AppCompatImageView source = view.findViewById(R.id.iv_source);
                            Pair<View,String> pair1 = new Pair<>((View)title,ViewCompat.getTransitionName(title));
                            Pair<View,String> pair2 = new Pair<>((View)source,ViewCompat.getTransitionName(source));

                            Intent intent = new Intent(MainActivity.this,DetailActivity.class);
                            intent.putExtra(TAG,view.getTransitionName());
                            intent.putExtra("article",article.getLink());
                            intent.putExtra("title",article.getTitle());
                            intent.putExtra("source",article.getSource());
                            startActivity(intent,
                                    ActivityOptions.makeSceneTransitionAnimation(MainActivity.this,
                                            pair1,
                                            pair2
                                    ).toBundle());
//                            NotifyDialog dialog = new NotifyDialog(MainActivity.this,R.layout.layout_full_screen_web, Gravity.BOTTOM);
//                            WebView webView = dialog.findById(R.id.web);
//                            dialog.findById(R.id.btn_back).setOnClickListener(btn->{
//                                dialog.dismiss();
//                            });
//                            webView.getSettings().setJavaScriptEnabled(true);
//                            webView.loadUrl(article.getLink());
//                            dialog.setAutoDismiss(false);
//                            dialog.setCancelable(true);
//                            dialog.show();
                        });
                    });
                }
            });
        });

        mBind.btnHotKey.setOnClickListener(v->{
            String url = "https://www.wanandroid.com//hotkey/json";
            HttpUtil.sendRequest(url, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    JSONObject jsonObject = JSON.parseObject(response.body().string());
                    JSONArray array = jsonObject.getJSONArray("data");
                    List<HotKey> hotKeys = JSONObject.parseArray(array.toJSONString(), HotKey.class);
                    Log.e("TAG","" + hotKeys.size());
                    runOnUiThread(()->{
                        HotKeyAdapter adapter = new HotKeyAdapter(hotKeys);
                        mBind.recycler.setAdapter(adapter);
                    });
                }
            });
        });

        mBind.btnWxArticle.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, MainTestActivity.class);
            startActivity(intent);
        });

        mBind.btnLogin.setOnClickListener(v->{
            NotifyDialog login = new NotifyDialog(MainActivity.this,R.layout.layout_login,Gravity.BOTTOM);
            login.setCancelable(false);
            login.setAutoDismiss(false);
            login.setTouchMovable(false);
            login.findById(R.id.btn_login).setOnClickListener(btn->{
                String username = ((EditText)login.findById(R.id.et_username)).getText().toString();
                String password = ((EditText)login.findById(R.id.et_password)).getText().toString();
                String url = "https://www.wanandroid.com/user/login";
                RequestBody body = new FormBody.Builder().add("username", username).add("password", password).build();
                //RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf-8"), obj.toJSONString());
                HttpUtil.postRequest(url,body,new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        Log.e(TAG, "onResponse: " + response.body().string() );
                        login.dismiss();
                    }
                });
            });
            login.show();
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    private void updateColor() {
        int color = Color.WHITE;
        int text = Color.BLACK;
        if (!lightTheme) {
            color = Color.BLACK;
            text = Color.WHITE;
        }
        mBind.main.setBackgroundColor(color);
        for (View view : getChildView(mBind.main)) {
            if (view instanceof TextView) {
                ((TextView) view).setTextColor(text);
            } else {
                view.setBackgroundColor(color);
            }
        }
    }

    private View[] getChildView(ViewGroup viewGroup) {
        View[] mChildViews = new View[viewGroup.getChildCount()];
        for (int i = 0; i < mChildViews.length; i++) {
            mChildViews[i] = viewGroup.getChildAt(i);
        }
        return mChildViews;
    }

    public void authenticate(BiometricPrompt.CryptoObject crypto,
                             CancellationSignal cancel,
                             Executor executor,
                             BiometricPrompt.AuthenticationCallback callback) {

    }

    public void showBiometricPromptDialog(Context context) {
        final KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(
                Context.KEYGUARD_SERVICE);

        if (keyguardManager.isKeyguardSecure()) {
            final BiometricPrompt.AuthenticationCallback authenticationCallback =
                    new BiometricPrompt.AuthenticationCallback() {
                        @Override
                        public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
                            NotifyDialog notifyDialog = new NotifyDialog(MainActivity.this, R.layout.layout_loaded, Gravity.CENTER);
                            notifyDialog.setOnShowListener(dialog -> ((TickView) notifyDialog.findById(R.id.tick)).toggle());
                            ((TickView) notifyDialog.findById(R.id.tick)).getConfig().setTickAnimatorListener(new TickAnimatorListener() {
                                @Override
                                public void onAnimationStart(TickView tickView) {
                                }

                                @Override
                                public void onAnimationEnd(TickView tickView) {
                                    new Handler(Looper.getMainLooper()).postDelayed(notifyDialog::dismiss, 200);

                                }
                            });
                            notifyDialog.show();
                            Log.d("TAG", "onAuthenticationSucceeded: ");
                        }

                        @Override
                        public void onAuthenticationError(int errorCode, CharSequence errString) {
                            //Do nothing
                            Toast.makeText(getApplicationContext(), "onAuthenticationError: " + errorCode + ", str: " + errString, Toast.LENGTH_SHORT).show();
                            Log.d("TAG", "onAuthenticationError: " + errorCode + ", str: " + errString);
                        }
                    };


            final Handler handler = new Handler(Looper.getMainLooper());

            final BiometricPrompt.Builder builder = new BiometricPrompt.Builder(context)
                    .setTitle("要不,按个指纹?")
                    .setNegativeButton("No", runnable -> handler.post(runnable), (dialog, which) -> {
                        Log.d("TAG", "showLockScreen: negative btn clicked, do nothing");
                    })
                    .setSubtitle("按一下吧");

            if (keyguardManager.isDeviceSecure()) {
                builder.setDeviceCredentialAllowed(false);
            }

            final BiometricPrompt bp = builder.build();
            bp.authenticate(new CancellationSignal(),
                    runnable -> handler.post(runnable),
                    authenticationCallback);
        } else {
            Toast.makeText(getApplicationContext(), "没有设置任何密码", Toast.LENGTH_SHORT).show();
            Log.d("TAG", "showLockScreen:  no in scrue.... no password");
        }
    }


    private void registerInstallAppBroadcastReceiver() {
        Log.e(TAG, "registerInstallAppBroadcastReceiver: " );
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        intentFilter.addDataScheme("package");
        this.registerReceiver(mInstallAppBroadcastReceiver, intentFilter);
    }

    private final BroadcastReceiver mInstallAppBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG, "onReceive: " + intent.getAction() );
            if(intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)){
                if(intent.getData().getSchemeSpecificPart().equals("com.blackshark.gamesdkapp")){
                    //检查登录 or 自动登录
                }
            }
            if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {
                if(intent.getData().getSchemeSpecificPart().equals("com.blackshark.gamesdkapp")){
                    //检查登录 or 自动登录
                }
            }
        }
    };

}